package com.itheima.impl;

import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import pojo.Permission;
import pojo.Role;
import pojo.User;

import java.util.Set;

/**
 * 用户服务
 */
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    
    //根据用户名查询用户
    @Override
    public User findUserByUsername(String username) {
        User user = userDao.findUserByUsername(username);
        if(user == null){
            return null;
        }
        //根据用户id查询对应哪些角色
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findRolesByUserId(userId);// []
        
        if(roles != null && roles.size() > 0){
            for (Role role : roles) {
                
                //根据角色id查询对应哪些权限
                Set<Permission> permissions = permissionDao.findPermissionsByRoleId(role.getId());
                if(permissions != null && permissions.size() > 0){
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }
}
